package com.pool.store;

import java.util.List;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.pool.common.Lists;
import com.pool.common.Maps;
import com.pool.store.gdata.GDataFactory;

/**
 * @author claveld@gmail.com (David Clavel)
 */
public class SpreadsheetsXmlHandler<E> extends DefaultHandler {

  private static final String ENTRY = "entry";
  private static final String FIELD = "field";

  private final GDataFactory<E> elementFactory;
  
  private List<E> elts;
  private Map<String, String> values;
  
  private boolean inField = false;
  private String currentNameAttribute = "";

  public SpreadsheetsXmlHandler(GDataFactory<E> elementFactory) {
    this.elementFactory = elementFactory;
  }
  
  @Override
  public void startDocument() throws SAXException {
    elts = Lists.newArrayList();
    values = Maps.newHashMap();
  }

  @Override
  public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    if (FIELD.equals(localName)) {
      inField = true;
      currentNameAttribute = attributes.getValue("name");
    }
  }

  @Override
  public void endElement(String uri, String localName, String qName) throws SAXException {
    if (ENTRY.equals(localName)) {
      elts.add(elementFactory.createFrom(values));
      values.clear();
    } else if (FIELD.equals(localName)) {
      inField = false;
    }
  }

  @Override
  public void characters(char[] ch, int start, int length) throws SAXException {
    if (inField) {
      String previousValue = "";
      if (values.containsKey(currentNameAttribute)) {
        previousValue = values.get(currentNameAttribute);
      }
      values.put(currentNameAttribute, previousValue + new String(ch, start, length));
    }
  }

  public List<E> getAll() {
    return elts;
  }
}